﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using ModeloGaleriaNET;
using CADs;
using SeguridadGaleria;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para TematicasWindow.xaml
    /// </summary>
    public partial class TematicasWindow : Window
    {
        private List<string> tematicasOriginal;
        private List<string> tematicasAdded;
        private List<string> tematicasDeleted;
        private BackgroundWorker worker;
        private TematicasData data;
        private dynamic tematicas;
        private bool? success;

        public TematicasWindow()
        {
            InitializeComponent();
            data = TematicasData.Instance;
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        public List<string> TematicasAdded
        {
            get { return tematicasAdded; }
        }

        public List<string> TematicasDeleted
        {
            get { return tematicasDeleted; }
        }

        public bool? Success
        {
            get { return success; }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            tematicas = new TematicaCAD().GetTematicaSoloNombre();
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            String s;
            Xceed.Wpf.Toolkit.Primitives.SelectorItem item;
    
            if (tematicas != null)
            {
                foreach (object t in tematicas)
                {
                    item = new Xceed.Wpf.Toolkit.Primitives.SelectorItem();
                    s = Convert.ToString(t.GetType().GetProperty("Nombre").GetValue(t, null));
                    item.Content = s;
                    clbTematicas.Items.Add(item);
                }
                foreach (Xceed.Wpf.Toolkit.Primitives.SelectorItem it in clbTematicas.Items)
                {
                    s = Convert.ToString(it.GetType().GetProperty("Content").GetValue(it, null));
                    if (tematicasOriginal.Contains(s))
                        it.GetType().GetProperty("IsSelected").SetValue(it, true, null);
                }
            }
        }

        private bool HasChanges()
        {
            List<string> listaActual;
            
            // Rellenamos la lista actual de las temáticas seleccionadas
            listaActual = new List<string>();
            foreach (object item in clbTematicas.Items)
            {
                if (Convert.ToBoolean(item.GetType().GetProperty("IsSelected").GetValue(item, null)))
                    listaActual.Add(Convert.ToString(item.GetType().GetProperty("Content").GetValue(item, null)));
            }

            // Vemos las temáticas nuevas que hay (contenidas en la nueva y no en la original)
            tematicasAdded = new List<string>();
            foreach (string s in listaActual)
            {
                if (!tematicasOriginal.Contains(s))
                    tematicasAdded.Add(s);
            }

            // Vemos las temáticas que se han borrado (contenidas en la original y no en la nueva)
            tematicasDeleted = new List<string>();
            foreach (string s in tematicasOriginal)
            {
                if (!listaActual.Contains(s))
                    tematicasDeleted.Add(s);
            }

            return tematicasDeleted.Count > 0 || tematicasAdded.Count > 0;
        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            success = false;
            Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tematicasOriginal = data.Tematicas;
            if (!worker.IsBusy)
                worker.RunWorkerAsync();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (success == false)
            {
                if (HasChanges())
                {
                    if (Xceed.Wpf.Toolkit.MessageBox.Show("¿Desea salir sin guardar los cambios", "Salir sin guardar",
                        MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                        e.Cancel = true;
                }
            }
        }

        private void btAceptar_Click(object sender, RoutedEventArgs e)
        {
            if (HasChanges())
            {
                if (clbTematicas.SelectedItems.Count == 0)
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Debes seleccionar al menos una temática", "Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                tematicasOriginal.AddRange(tematicasAdded);
                foreach (string s in tematicasDeleted)
                    tematicasOriginal.Remove(s);
                data.Save(tematicasOriginal);
            }
            success = true;
            Close();
        }
    }
}
